package edu.zut.main.thread;

public class TicketDemo {

    public static void main(String[] args) {
        SaleTicket saleTicket = new SaleTicket();
        TicketSaleThread thread1 = new TicketSaleThread(saleTicket);
        TicketSaleThread thread2 = new TicketSaleThread(saleTicket);
        TicketSaleThread thread3 = new TicketSaleThread(saleTicket);

        new Thread(thread1,"小张").start();
        new Thread(thread3,"小李子").start();
        new Thread(thread2,"小娄").start();
    }

}

class TicketSaleThread implements Runnable{

    private SaleTicket saleTicket;

    public TicketSaleThread(SaleTicket saleTicket) {
        this.saleTicket = saleTicket;
    }

    @Override
    public void run() {
        while (true){
            synchronized (saleTicket) {
                if (saleTicket.getTicketNum() <= 0) {
                    System.out.println(Thread.currentThread().getName() + "余票不足");
                    break;
                }
                saleTicket.sale();
            }
        }
    }
}


class SaleTicket{

    private int ticketNum = 10;

    public int getTicketNum() {
        return ticketNum;
    }

    //售票
    public void sale(){
        System.out.println(Thread.currentThread().getName() + "售出了第" + ticketNum + "张票");
        ticketNum--;
    }
}

//模拟三个人抢5个苹果
